package com.leejxx.health.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leejxx.health.dao.CheckGroupDao;
import com.leejxx.health.entity.PageResult;
import com.leejxx.health.entity.QueryPageBean;
import com.leejxx.health.exception.BusinessRuntimeException;
import com.leejxx.health.pojo.CheckGroup;
import com.leejxx.health.pojo.CheckItem;
import com.leejxx.health.service.CheckGroupService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @Author LeeJx
 * @ClassName CheckGroupServiceImpl
 * @Description TODO
 * @date 2020/12/31 18:11
 * @Version 1.0
 */
@DubboService
@Slf4j
public class CheckGroupServiceImpl implements CheckGroupService {
    @Autowired
    private CheckGroupDao checkGroupDao;

    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<CheckGroup> page = checkGroupDao.findByCondition(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public void add(CheckGroup checkGroup, List<Integer> checkItemIds) {
        if (checkGroup.getCode() == null || checkGroup.getName() == null) {
            throw new BusinessRuntimeException("code和name不能为空，请重新输入");
        }

        List<String> allCodes = checkGroupDao.findAllCodes();

        for (String code : allCodes) {
            if (checkGroup.getCode().equals(code)) {
                throw new BusinessRuntimeException("当前编码已被使用，请重新输入");
            }
        }
        checkGroupDao.add(checkGroup);

        checkGroupDao.addCheckItemIds(checkGroup.getCode(), checkItemIds);
    }

    @Override
    public List<CheckItem> findCheckItem() {
        return checkGroupDao.findCheckItem();
    }

    @Override
    public CheckGroup findById(Integer checkGroupId) {
        CheckGroup checkGroup = checkGroupDao.findById(checkGroupId);
        List<CheckItem> checkItems = checkGroupDao.findCheckItemsOfCheckGroup(checkGroupId);
        checkGroup.setCheckItems(checkItems);
        return checkGroup;
    }

    @Override
    public void edit(CheckGroup checkGroup, List<Integer> checkItemIds) {
        //先删除关系
        checkGroupDao.deleteGroupIdAndItemId(checkGroup.getId());
        //在修改检查项
        checkGroupDao.edit(checkGroup);
        //再添加关系
        checkGroupDao.addCheckItemIds(checkGroup.getCode(), checkItemIds);
    }

    @Override
    public void delete(Integer checkGroupId) {
        long itemCount = checkGroupDao.findItemCount(checkGroupId);
        long meatCount = checkGroupDao.findMeatCount(checkGroupId);
        if (itemCount > 0 || meatCount > 0) {
            throw new BusinessRuntimeException("当前检查组有数据，无法删除");
        }

        checkGroupDao.deleteGroup(checkGroupId);
    }
}
